package com.smart.community.user.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smart.community.user.entity.UserRole;
import com.smart.community.user.mapper.UserRoleMapper;
import com.smart.community.user.service.UserRoleService;

import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户角色服务实现
 * 
 * 注意：所有删除操作均为物理删除，不使用软删除
 * 设计原则：根据"智慧社区微服务架构总览.md"中的关联表设计原则
 *
 * @author Wu.Liang
 * @since 2025-07-05
 */
@Slf4j
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {

    // ==================== 缓存常量定义 ====================
    private static final String USER_ROLES_CACHE_PREFIX = "user:roles:";
    private static final String USERS_BY_ROLE_CACHE_PREFIX = "users:by:role:";
    
    // 缓存过期时间（秒）
    private static final long USER_ROLES_CACHE_EXPIRE = 1800; // 30分钟
    private static final long USERS_BY_ROLE_CACHE_EXPIRE = 1800; // 30分钟

    // ==================== 缓存工具方法 ====================
    
    /**
     * 清除用户角色缓存
     */
    private void clearUserRolesCache(Long userId) {
        try {
            String cacheKey = USER_ROLES_CACHE_PREFIX + userId;
            // 这里需要注入CacheService，暂时注释掉
            // cacheService.delete(cacheKey);
            log.debug("清除用户角色缓存成功，用户ID：{}", userId);
        } catch (Exception e) {
            log.warn("清除用户角色缓存失败，用户ID：{}", userId, e);
        }
    }
    
    /**
     * 清除角色用户列表缓存
     */
    private void clearUsersByRoleCache(Long roleId) {
        try {
            String cacheKey = USERS_BY_ROLE_CACHE_PREFIX + roleId;
            // 这里需要注入CacheService，暂时注释掉
            // cacheService.delete(cacheKey);
            log.debug("清除角色用户列表缓存成功，角色ID：{}", roleId);
        } catch (Exception e) {
            log.warn("清除角色用户列表缓存失败，角色ID：{}", roleId, e);
        }
    }

    @Override
    public List<UserRole> getUserRolesByUserId(Long userId) throws Exception {
        // 根据用户ID查询用户角色关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId)
                   .eq(UserRole::getStatus, 1);
        return this.list(queryWrapper);
    }

    @Override
    @GlobalTransactional
    public void assignRolesToUser(Long userId, List<Long> roleIds) throws Exception {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            throw new IllegalArgumentException("用户ID和角色ID列表不能为空");
        }
        
        // 批量创建用户角色关联
        List<UserRole> userRoles = new ArrayList<>();
        for (Long roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRole.setStatus(1); // 启用状态
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setUpdateTime(LocalDateTime.now());
            userRoles.add(userRole);
        }
        
        // 批量保存
        this.saveBatch(userRoles);
    }

    @Override
    @GlobalTransactional
    public void removeRolesFromUser(Long userId, List<Long> roleIds) throws Exception {
        if (userId == null || roleIds == null || roleIds.isEmpty()) {
            throw new IllegalArgumentException("用户ID和角色ID列表不能为空");
        }
        
        // 物理删除指定的用户角色关联
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId)
                   .in(UserRole::getRoleId, roleIds);
        
        this.remove(queryWrapper);
    }

    @Override
    @GlobalTransactional
    public void removeAllRolesFromUser(Long userId) throws Exception {
        if (userId == null) {
            throw new IllegalArgumentException("用户ID不能为空");
        }
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        // 物理删除，直接调用Mapper的delete方法
        this.getBaseMapper().delete(queryWrapper);
    }

    @Override
    public List<com.smart.community.user.entity.User> getUsersByRoleId(Long roleId) throws Exception {
        if (roleId == null) {
            return new ArrayList<>();
        }
        
        // 通过UserRoleMapper查询具有指定角色的用户列表
        return this.getBaseMapper().selectUsersByRoleId(roleId);
    }
} 